package org.jeecgframework.web.service.impl;
import java.io.Serializable;
import java.util.*;

import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.CbsProcurementNoteServiceI;
import org.jeecgframework.web.service.ZyContactsServiceI;
import org.jeecgframework.web.service.ZyEquipmentSpareServiceI;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("cbsProcurementNoteService")
@Transactional
public class CbsProcurementNoteServiceImpl extends CommonServiceImpl implements CbsProcurementNoteServiceI {

    @Autowired
    private ZyContactsServiceI zyContactsService;

    @Autowired
    private ZyEquipmentSpareServiceI zyEquipmentSpareService;
	
 	public <T> void delete(T entity) {
 		super.delete(entity);
 		//执行删除操作配置的sql增强
		this.doDelSql((CbsProcurementNoteEntity)entity);
 	}
 	
 	public <T> Serializable save(T entity) {
 		Serializable t = super.save(entity);
 		//执行新增操作配置的sql增强
 		this.doAddSql((CbsProcurementNoteEntity)entity);
 		return t;
 	}
 	
 	public <T> void saveOrUpdate(T entity) {
 		super.saveOrUpdate(entity);
 		//执行更新操作配置的sql增强
 		this.doUpdateSql((CbsProcurementNoteEntity)entity);
 	}
 	
 	/**
	 * 默认按钮-sql增强-新增操作
	 * @return
	 */
 	public boolean doAddSql(CbsProcurementNoteEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-更新操作
	 * @return
	 */
 	public boolean doUpdateSql(CbsProcurementNoteEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-删除操作
	 * @return
	 */
 	public boolean doDelSql(CbsProcurementNoteEntity t){
	 	return true;
 	}

    @Override
    public List<CbsProcurementNoteEntity> findProcurementByCinema(String cinemaId) {
        return findHql("from CbsProcurementNoteEntity where cinema.id=? order by state asc,createDate desc",cinemaId);
    }

    @Override
    public List<CbsProcurementNoteEntity> findProcurementByContactCinema(String userName) {
        ZyContactsEntity contact = zyContactsService.findContactByUserName(userName);
        List<CbsProcurementNoteEntity> notes = new ArrayList<CbsProcurementNoteEntity>();
        if(contact.getBelongCinema() != null){
            notes = findProcurementByCinema(contact.getBelongCinema().getId());
        }
        return notes;
    }



    public synchronized  String genProcurementNo() {
        String currentMaxNo = "";
//        Map<String,Object> maxNo = new HashMap<String,Object>();
//        maxNo.put("no","SA16100103");
        Map<String,Object> maxNo = findOneForJdbc("SELECT max(procument_no) as no FROM `cbs_procurement_note`");
        if(maxNo != null){
            currentMaxNo = oConvertUtils.getString(maxNo.get("no"));
            if(currentMaxNo.length()>=10 && currentMaxNo.contains(StaticValue.PROCUREMENT_NO_PRE)){
                int tempNo = oConvertUtils.getInt(currentMaxNo.substring(4));
                currentMaxNo = StaticValue.PROCUREMENT_NO_PRE + DateUtils.formatDate(new Date(),"yyyy").substring(2)
                        +StringUtil.paddingCharacter("left",6,"0",tempNo+1);
            }
        }
        return StringUtil.isEmpty(currentMaxNo)?StaticValue.PROCUREMENT_NO_PRE + DateUtils.formatDate(new Date(),"yyyy").substring(2)+"000001":currentMaxNo;
    }

    @Override
    public CbsProcurementNoteEntity setNotePriceAndPartShowPrice(CbsProcurementNoteEntity note) {
        if (note == null || note.getPartList().size() == 0) {
            return null;
        }
        for (CbsProcurementPartEntity procurementPart : note.getPartList()) {
            String bpType = zyEquipmentSpareService.checkBP(note.getPaertEsList().get(0).getEquipmentSpare().getBpNo());
            setPartPriceWithType(procurementPart,bpType);
        }
        return note;
    }

    public CbsProcurementPartEntity setNotePartPrice(CbsProcurementPartEntity notePart) {
        return setPartPriceWithType(notePart,"");
    }

    public CbsProcurementPartEntity setPartPriceWithType(CbsProcurementPartEntity notePart,String bpType) {
        if(notePart == null){
            return notePart;
        }
        CbsPartInfoEntity part = notePart.getPartInfo();
        if(part == null){
            return notePart;
        }
        Double price = part.getTerminalPrice();
        CbsProcurementNoteEntity note = notePart.getProcurement();
        if(StaticValue.CBS_PARTINFO_SORT.equals(part.getCommodity())){
        	if ("2".equals(note.getSource()) || "3".equals(note.getSource())) {
        		price = part.getWechatPrice();
        	} else {
        		price = part.getCinemaPrice();
        	}
        }else{
            if(note == null){
                return notePart;
            }
            if(StringUtil.isEmpty(bpType)){
                if(note.getPaertEsList() == null || note.getPaertEsList().size() == 0){
                    notePart.setPrice(part.getWechatPrice());
                    return notePart;
                }
                bpType = zyEquipmentSpareService.checkBP(note.getPaertEsList().get(0).getEquipmentSpare().getBpNo());
            }
            if ("z".equals(bpType)) {
                price = part.getCfgcPrice();
            }else if("h".equals(bpType)){
                price = part.getHdPrice();
            }else if("2".equals(note.getSource()) || "3".equals(note.getSource())){
                price = part.getWechatPrice();
            }
        }
        notePart.setPrice(price);
        return notePart;
    }

    @Override
    public CbsProcurementNoteEntity handleNoteInvoice(CbsProcurementNoteEntity note, String invoiceId) {
        /*更新发票基本信息*/
        /*if(StringUtil.isNotEmpty(invoiceId)){
            CbsInvoiceInfoEntity invoice = get(CbsInvoiceInfoEntity.class,invoiceId);
            if(invoice != null && note.getInvoice() != null){
                CbsInvoiceSnapEntity snap = note.getInvoice();
                invoice.setClientTaxnum(snap.getClientTaxnum());
                invoice.setClientBankname(snap.getClientBankname());
                invoice.setClientBankaccount(snap.getClientBankaccount());
                invoice.setInvoiceTitle(snap.getInvoiceTitle());
                super.saveOrUpdate(invoice);
            }
        }*/
        if(null != note.getInvoice()){
            /*第三方*/
            if("1".equals(note.getClientType())){
                note.getInvoice().setGenre(StaticValue.DIC_GENRE_AGENCY);
                note.getInvoice().setBelongOrg(get(TSDepart.class,note.getProcurement().getId()));
            }else{//客户
                note.getInvoice().setGenre(StaticValue.DIC_GENRE_CINEMA);
                note.getInvoice().setBelongCinema(get(ZyCinemaEntity.class,note.getCinema().getId()));
            }
            if(StringUtil.isNotEmpty(note.getInvoice().getId())){
                super.updateEntitie(note.getInvoice());
            }else{
                super.save(note.getInvoice());
            }
        }
        return note;
    }

//    public static void main(String[] args){
//        CbsProcurementNoteServiceImpl s = new CbsProcurementNoteServiceImpl();
//        System.out.print(s.genProcurementNo());
//    }
    /**
	 * 替换sql中的变量
	 * @param sql
	 * @return
	 */
 	public String replaceVal(String sql,CbsProcurementNoteEntity t){
 		sql  = sql.replace("#{id}",String.valueOf(t.getId()));
 		sql  = sql.replace("#{client_type}",String.valueOf(t.getClientType()));
 		sql  = sql.replace("#{procurement}",String.valueOf(t.getProcurement()));
// 		sql  = sql.replace("#{cinema_id}",String.valueOf(t.getCinemaId()));
// 		sql  = sql.replace("#{linkman_id}",String.valueOf(t.getLinkmanId()));
 		sql  = sql.replace("#{is_onsite_services}",String.valueOf(t.getIsOnsiteServices()));
 		sql  = sql.replace("#{service_place}",String.valueOf(t.getServicePlace()));
 		sql  = sql.replace("#{warranty}",String.valueOf(t.getWarranty()));
 		sql  = sql.replace("#{services_premise}",String.valueOf(t.getServicesPremise()));
 		sql  = sql.replace("#{comment}",String.valueOf(t.getComment()));
 		sql  = sql.replace("#{services_des}",String.valueOf(t.getServicesDes()));
 		sql  = sql.replace("#{source}",String.valueOf(t.getSource()));
 		sql  = sql.replace("#{state}",String.valueOf(t.getState()));
 		sql  = sql.replace("#{create_name}",String.valueOf(t.getCreateName()));
 		sql  = sql.replace("#{create_by}",String.valueOf(t.getCreateBy()));
 		sql  = sql.replace("#{create_date}",String.valueOf(t.getCreateDate()));
 		sql  = sql.replace("#{update_name}",String.valueOf(t.getUpdateName()));
 		sql  = sql.replace("#{update_by}",String.valueOf(t.getUpdateBy()));
 		sql  = sql.replace("#{update_date}",String.valueOf(t.getUpdateDate()));
 		sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
 		return sql;
 	}
}